/*
 * @lc app=leetcode.cn id=1763 lang=typescript
 *
 * [1763] 最长的美好子字符串
 */

// @lc code=start
function longestNiceSubstring(s: string): string {
  const n = s.length;
  let maxPos = 0;
  let maxLen = 0;

  const lowerBase = 'a'.charCodeAt(0);
  const upperBase = 'A'.charCodeAt(0);

  for (let i = 0; i < n; i++) {
    // 位标记
    let lower_bit = 0;
    let upper_bit = 0;

    for (let j = i; j < n; j++) {
      // 出现过的字符，将对应位置标记为1
      if ('a' <= s[j] && s[j] <= 'z') {
        lower_bit |= 1 << (s[j].charCodeAt(0) - lowerBase);
      } else if ('A' <= s[j] && s[j] <= 'Z') {
        upper_bit |= 1 << (s[j].charCodeAt(0) - upperBase);
      }
      // 对比位标记
      // 对比位置长度是否大于当前最大长度
      if (lower_bit === upper_bit && j - i + 1 > maxLen) {
        maxPos = i;
        maxLen = j - i + 1;
      }
    }
  }

  return s.substring(maxPos, maxPos + maxLen);
}
// @lc code=end
